import 'dart:io';
import 'package:args/args.dart';
import 'package:uuid/uuid.dart';
import '../models/ssh_connection.dart';
import 'database_service.dart';
import 'ssh_service.dart';

class CLIService {
  final _uuid = const Uuid();
  final _databaseService = DatabaseService();
  final _sshService = SSHService();

  Future<void> handleCommandLineArgs() async {
    final args = List<String>.from(Platform.executableArguments);
    
    // 移除flutter相关参数
    args.removeWhere((arg) => arg.startsWith('--') || arg.startsWith('flutter'));
    
    if (args.isEmpty) return;

    final parser = ArgParser()
      ..addOption('host', abbr: 'h', help: 'SSH服务器地址')
      ..addOption('port', abbr: 'p', defaultsTo: '22', help: 'SSH端口')
      ..addOption('username', abbr: 'u', help: '用户名')
      ..addOption('password', abbr: 'w', help: '密码')
      ..addOption('key', abbr: 'k', help: '私钥文件路径')
      ..addOption('passphrase', abbr: 's', help: '私钥密码')
      ..addOption('command', abbr: 'c', help: '要执行的命令')
      ..addOption('script', abbr: 'f', help: '脚本文件路径')
      ..addFlag('help', abbr: 'H', help: '显示帮助信息', negatable: false)
      ..addFlag('save', help: '保存连接配置', negatable: false);

    try {
      final results = parser.parse(args);

      if (results['help']) {
        _printHelp(parser);
        exit(0);
      }

      await _executeFromCLI(results);
    } catch (e) {
      print('参数错误: $e');
      _printHelp(parser);
      exit(1);
    }
  }

  void _printHelp(ArgParser parser) {
    print('''
CLSSH - SSH客户端命令行工具

使用方法:
  clssh [选项]

选项:
${parser.usage}

示例:
  # 直接执行命令
  clssh -h 192.168.1.100 -u root -p 22 -c "ls -la"
  
  # 使用私钥连接
  clssh -h example.com -u user -k ~/.ssh/id_rsa -c "uptime"
  
  # 执行脚本文件
  clssh -h server.com -u admin -f deploy.sh --save
  
  # 保存连接配置
  clssh -h 192.168.1.100 -u root --save
''');
  }

  Future<void> _executeFromCLI(ArgResults results) async {
    final host = results['host'] as String?;
    final username = results['username'] as String?;

    if (host == null || username == null) {
      print('错误: 必须指定主机地址(--host)和用户名(--username)');
      exit(1);
    }

    final port = int.parse(results['port'] as String);
    final password = results['password'] as String?;
    final keyPath = results['key'] as String?;
    final passphrase = results['passphrase'] as String?;
    final command = results['command'] as String?;
    final scriptPath = results['script'] as String?;

    // 查找或创建连接配置
    final connections = await _databaseService.getConnections();
    SSHConnection? connection = connections.firstWhere(
      (c) => c.host == host && c.username == username,
      orElse: () => SSHConnection(
        id: _uuid.v4(),
        name: '$username@$host',
        host: host,
        port: port,
        username: username,
        password: password,
        privateKeyPath: keyPath,
        passphrase: passphrase,
      ),
    );

    // 如果指定了新参数，更新连接配置
    connection = connection.copyWith(
      port: port,
      password: password,
      privateKeyPath: keyPath,
      passphrase: passphrase,
    );

    if (results['save']) {
      await _databaseService.saveConnection(connection);
      print('连接配置已保存: ${connection.name}');
    }

    // 连接到服务器
    print('正在连接到 ${connection.name}...');
    final connected = await _sshService.connect(connection);
    
    if (!connected) {
      print('连接失败');
      exit(1);
    }

    try {
      List<String> commands = [];
      
      if (scriptPath != null) {
        final scriptFile = File(scriptPath);
        if (!scriptFile.existsSync()) {
          print('脚本文件不存在: $scriptPath');
          exit(1);
        }
        commands = await scriptFile.readAsLines();
      } else if (command != null) {
        commands = [command];
      } else {
        print('错误: 必须指定要执行的命令(--command)或脚本文件(--script)');
        exit(1);
      }

      print('开始执行命令...');
      final results = await _sshService.executeScript(commands);

      for (final result in results) {
        print('\n--- 命令: ${result.command} ---');
        print(result.output);
        print('退出码: ${result.exitCode}');
        
        // 保存命令历史
        await _databaseService.saveCommandHistory(result);
      }

    } finally {
      await _sshService.disconnect();
    }

    exit(0);
  }
}